package edu.ustb.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.ustb.domain.user.UserAddress;
import edu.ustb.service.user.Impl.UsersServiceImpl;
import edu.ustb.service.user.UsersService;
import edu.ustb.utils.JsonUtil;
import edu.ustb.view.JsonData;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "UserAddressFindController", value = "/users/findAddress")
public class UserAddressFindController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain;charset=utf-8");
        //从request域中获得json中的信息
        System.out.println("到达control");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = JsonUtil.toJSONOb(request.getInputStream());
        String userPhone = jsonObject.getString("userPhone");
        System.out.println(userPhone);
        //用userPhone作为标识符到数据库中查询地址
        UsersService usersService = new UsersServiceImpl();
        List<UserAddress> userAddressList = usersService.findAddress(userPhone);
        System.out.println("地址列表");
        System.out.println(userAddressList);
        //转成jsondata
        JsonData result = JsonData.success("查询成功",userAddressList);
        out.write(JSON.toJSONString(result));
        System.out.println("查询地址成功");
        out.flush();
        out.close();
    }
}
